<template>
  <n-cascader v-bind="props" :options="categoryOptions" style="min-width: 194px" @load="handleCategoryLoad" />
</template>

<script lang="ts">
  import { defineComponent, reactive, toRefs } from 'vue'
  import { NCascader } from 'naive-ui'
  import { useStore } from '@/store'

  export default defineComponent({
    name: 'XProductCategory',
    components: {
      NCascader
    },
    props: {
      ...NCascader.props,
      clearable: {
        type: Boolean,
        default: true
      },
      remote: {
        type: Boolean,
        default: true
      },
      placeholder: {
        type: String,
        default: '请选择商品类目'
      },
      action: {
        type: String,
        default: 'product/getProductCategory'
      }
    },
    setup($props, { emit: $emit }) {
      const $store = useStore()
      const $state = reactive({
        props: toRefs($props) || {},
        // 类目
        categoryOptions: []
      })

      // 加载类目数据
      const getCategoryList = async (id: null | number) => {
        return new Promise<void>((resolve) => {
          $store
            .dispatch($props.action, {
              parentId: id || null
            })
            .then((res) => {
              const list = res.data
                ? res.data.map((item: { id: number; categoryName: string; hasChild: boolean }) => {
                    return {
                      ...item,
                      label: item.categoryName,
                      value: item.id,
                      isLeaf: !item.hasChild
                    }
                  })
                : []
              // 初始化
              if (!id) {
                $state.categoryOptions = list
              }
              resolve(list)
            })
        })
      }
      // 加载一级
      getCategoryList(null)

      // 加载下一级
      const handleCategoryLoad = (option: { id: number; children: any }) => {
        return new Promise<void>(async (resolve) => {
          option.children = await getCategoryList(option.id)
          resolve()
        })
      }

      return {
        ...toRefs($state),
        handleCategoryLoad
      }
    }
  })
</script>

<style lang="scss" scoped>
  .n-form--inline {
    &.is-wrap {
      flex-wrap: wrap;
    }
  }
</style>
